﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

namespace HPortal.Backend
{
    public partial class ArticleEdit : System.Web.UI.Page
    {
        public int ArticleID = HtmlHelper.GetIdFromRequestString("ArticleID", -1);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindcboChannel();
                BindPanelList();
                if (this.ArticleID != -1)
                {
                    SqlDataReader dr = DatabaseHelper.SelectReader(null, "Article", "ArticleID=" + ArticleID);
                    while (dr.Read())
                    {
                        txtTitle.Text = dr["Title"].ToString();
                        txtHead.Text = dr["Head"].ToString();
                        txtContent.Value = dr["Content"].ToString();
                        txtPublishTime.Text = ((DateTime)dr["PublishedTime"]).ToString("MM/dd/yyyy");
                        txtExpireTime.Text = ((DateTime)dr["ExpiredTime"]).ToString("MM/dd/yyyy");
 
                        cmdAddArticle.Text = "Lưu bài";
                    }
                    dr.Close();
                    int PanelID = DatabaseHelper.SelectScalarInt("PanelID", "PanelList", "ItemID=" + ArticleID);
                    cboChannelList.SelectedValue  = DatabaseHelper.SelectScalarInt("ChannelID", "Panel", "PanelID=" + PanelID).ToString();
                    cboPanelList.SelectedValue = PanelID.ToString();
                    cmdDelete.Visible = true;
                    cboChannelList.Enabled = false;
                    cboPanelList.Enabled = false;
                    if (!checkPermission(int.Parse(cboChannelList.SelectedValue), "Edited") || !checkPermission(int.Parse(cboChannelList.SelectedValue), "Approved") || !checkPermission(int.Parse(cboChannelList.SelectedValue), "Administrated"))
                    {
                        Response.Redirect("ChannelList.aspx");
                    }
                }
                else
                {
                    //INSERT
                    txtPublishTime.Text = DateTime.Now.ToString("MM/dd/yyyy") ;
                    txtExpireTime.Text = (DateTime.Now.AddMonths(3)).ToString("MM/dd/yyyy");
                    cmdDelete.Visible = false;
                }
            }
            bool requireApprove = DatabaseHelper.SelectScalarBool("RequireApprove", "Channel", "ChannelID =" + cboChannelList.SelectedValue);
            if (requireApprove && !checkPermission(int.Parse(cboChannelList.SelectedValue), "Approved"))
            {
                cmdPublic.Visible = false;
            }
            else
                cmdPublic.Visible = true;
        }

        private DataTable getChannel()
        {
            try
            {
                string where = string.Empty;
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                    foreach (string roleName in arrRoleName)
                    {
                        where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                    }

                }
                where = where.Remove(where.Length - 1);
                where = "WHERE ChannelID IN (SELECT DISTINCT ChannelID FROM [ChannelRole] WHERE ([Role] IN (" + where + ")AND (Edited=1 OR Approved=1 OR Administrated=1)))";
                string query = "SELECT * FROM [Channel] " + where + " ORDER BY [ParentID],[Priority],[ChannelID]";
                return DatabaseHelper.Select(query);
            }
            catch
            {
                return null;
            }
        }
        protected void BindcboChannel()
        {
            this.cboChannelList.DataSource = getChannel();
            this.cboChannelList.DataValueField = "ChannelID";
            this.cboChannelList.DataTextField = "Name";
            this.cboChannelList.DataBind();
            cboChannelList.SelectedIndex = 0;
        }
        protected void BindPanelList()
        {
            cboPanelList.DataSource = DatabaseHelper.Select("exec getPanelList " + cboChannelList.SelectedValue);
            cboPanelList.DataValueField = "PanelID";
            cboPanelList.DataTextField = "Header";
            cboPanelList.DataBind();
        }
        protected void cboChannelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPanelList();
        }
        public void SaveArticle(int status)
        {
            string ImageType = flImage.PostedFile.ContentType;
            byte[] ImageContent = new byte[flImage.PostedFile.ContentLength];
            flImage.PostedFile.InputStream.Read(ImageContent, 0, ImageContent.Length);
            string Title = txtTitle.Text.Trim();
            string Head = txtHead.Text.Trim();
            string Content = txtContent.Value.Trim();
            string AuthorName = this.Context.User.Identity.Name;
            DateTime publishedTime = DateTime.Parse(txtPublishTime.Text);
            publishedTime = new DateTime(publishedTime.Year, publishedTime.Month, publishedTime.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            DateTime expiredTime = DateTime.Parse(txtExpireTime.Text);
            expiredTime = new DateTime(expiredTime.Year, expiredTime.Month, expiredTime.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            if (ArticleID == -1)//INSERT
            {
                int ArticleID_Identity = DatabaseHelper.InsertIdentity("TypeImage", "HeadImage", ImageContent, ImageType,
                    new string[] { "N@Title", "N@Head", "N@Content", "N@Author", "@ModifiedTime", "@PublishedTime", "@ExpiredTime", "@Status" },
                    new string[]{   Title,
                                    Head,
                                    Content,
                                    AuthorName,
                                    DateTime.Now.ToString(),
                                    publishedTime.ToString(),
                                    expiredTime.ToString(),
                                    status.ToString(),
                                }, "Article");
                DatabaseHelper.Insert("INSERT INTO [PanelList] ([ItemID],[PanelID]) VALUES (" + ArticleID_Identity + "," +cboPanelList.SelectedValue + ")");
            }
            else	// UPDATE
            {
                DatabaseHelper.Update("TypeImage", "HeadImage", ImageContent, ImageType,
                    new string[] { "N@Title", "N@Head", "N@Content", "N@Approver", "@ModifiedTime", "@PublishedTime", "@ExpiredTime", "@Status" },
                    new string[]{   Title,
                                    Head,
                                    Content,
                                    AuthorName,
                                    DateTime.Now.ToString(),
                                    publishedTime.ToString(),
                                    expiredTime.ToString(),
                                    status.ToString(),
                                }, "Article", "ArticleID=" + ArticleID);

            }
            Response.Redirect("ArticleList.aspx?ChannelID=" + cboChannelList.SelectedValue + "&PanelID=" + cboPanelList.SelectedValue);
        }

        protected void cmdAddArticle_Click(object sender, EventArgs e)
        {
            SaveArticle(1);
        }

        protected void cmdSubmit_Click(object sender, EventArgs e)
        {
            SaveArticle(2);
        }

        protected void cmdPublic_Click(object sender, EventArgs e)
        {
            if(chkTop.Checked ==true)
                SaveArticle(4);
            else
                SaveArticle(3);
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            if (ArticleID != -1)
            {
                DatabaseHelper.Delete("Article", "ArticleID=" + ArticleID);
                Response.Redirect("ArticleList.aspx?ChannelID=" + cboChannelList.SelectedValue + "&PanelID=" + cboPanelList.SelectedValue);

            }
        }
        private Boolean checkPermission(int ChannelID, string Permission)
        {
            string where = string.Empty;
            if (this.Context.User.Identity.IsAuthenticated)
            {
                string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                foreach (string roleName in arrRoleName)
                {
                    where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                }

            }
            where = where.Remove(where.Length - 1);
            string query = "SELECT count(*) FROM [ChannelRole] WHERE ([Role] IN (" + where + ") AND ChannelID=" + ChannelID + " AND " + Permission + "=1)";
            if (int.Parse(DatabaseHelper.SelectScalar(query).ToString()) > 0)
                return true;
            else
                return false;
        }

    }
}